﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class AttendanceWebForm_ExportAttendance : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ddlYYMM.DataBind();
        }
    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        VelocityUtil v = new VelocityUtil(@"~/App_Data/Attendance.xml");

        var db = new DB("Attendance");

        v.Put("d", ddlYYMM.Value);

        var empRow = new EmpManager(EmpManager.Current.EmpID);

        var emp = db.ExecuteRow(@"SELECT e.*, wg.WorkStartTime, wg.WorkEndTime FROM EmpData e
                        INNER JOIN WorkGroup wg ON e.WorkGroupID = wg.WorkGroupID 
                        WHERE e.EmpID = @EmpID", new DBParameter("EmpID", empRow["EmpID"]));

        LocManager.Current.Translate(emp, "EmpData", "EmpName");
        v.Put("emp", emp);


        var holidays = db.ExecuteListScalar<DateTime>(@"SELECT h.Date FROM Holiday h
                        INNER JOIN HolidayGroup hg ON h.HolidayGroupID = hg.HolidayGroupID
                        INNER JOIN WorkGroup wg ON hg.HolidayGroupID = wg.HolidayGroupID
                        WHERE Year(h.Date) = @yy AND wg.WorkGroupID = @WorkGroupID"
                        , new DBParameter("yy", ddlYYMM.Text.Year), new DBParameter("WorkGroupID", emp["WorkGroupID"]));

        v.Put("holidays", holidays);

        //var list = {

        var leaveData = db.Execute(@"SELECT ld.LeaveStartDate, ld.LeaveEndDate, ld.Hours FROM LeaveData ld
                        WHERE Year(ld.LeaveStartDate) = @yy AND EmpID = @EmpID AND Status = 'Y' ORDER BY ld.LeaveStartDate"
                        , new DBParameter("yy", ddlYYMM.Text.Year), new DBParameter("EmpID", empRow["empID"]));

        v.Put("leaveData", leaveData);

        var leaveDays = new[] { new { StartDate = DateTime.Now, EndDate = DateTime.Now, Hours = 0F } }.ToList().ToDictionary(data => data.StartDate.Date);

        leaveDays.Clear();

        foreach (DataRow dr in leaveData.Rows)
        {
            var startDate = (DateTime)dr["LeaveStartDate"];
            var endDate = (DateTime)dr["LeaveEndDate"];
            
            leaveDays.Add(startDate.Date, new { StartDate = startDate, EndDate = endDate, Hours = (float)dr["Hours"] });
        }
        
        v.Put("leaveDays", leaveDays);

        v.Download();
    }
}